package org.javaweb.cms_web.controller;

import org.javaweb.cms_web.model.Enum.UserStatus;
import org.javaweb.cms_web.model.User;
import org.javaweb.cms_web.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Date;


@Controller
public class TeamMemberRegisterController {

    @Autowired
    private UserService userService;

    // 显示注册页面
    @GetMapping("/teammember-register")
    public String register() {
        return "teammember-register";
    }

    // 处理注册请求
    @PostMapping("/teammember-register")
    public String register(@RequestParam String username,
                           @RequestParam String password,
                           @RequestParam String confirmPassword,
                           @RequestParam String email,
                           @RequestParam String phoneNumber,
                           @RequestParam String applicationReason,
                           @RequestParam String securityQuestion,
                           @RequestParam String securityAnswer,
                           @RequestParam Integer roleType,
                           Model model) {
        // 检查用户名是否已存在
        if (userService.getUserByNickname(username) != null) {
            model.addAttribute("error", "用户名已存在");
            return "teammember-register"; // 返回注册页面并显示错误信息
        }

        // 检查密码是否一致
        if (!password.equals(confirmPassword)) {
            model.addAttribute("error", "两次密码输入不一致");
            return "teammember-register"; // 返回注册页面并显示错误信息
        }

        //检查邮箱是否被使用
        if (userService.getUserByEmail(email) != null) {
            model.addAttribute("error", "该邮箱已经被使用");
            return "teammember-register"; // 返回注册页面并显示错误信息
        }

        // 创建新用户并保存
        User newUser = new User();
        newUser.setRoleType(roleType);
        newUser.setStatus(UserStatus.PENDING_REVIEW.getCode());
        newUser.setNickname(username);
        newUser.setPassword(password);
        newUser.setEmail(email);
        newUser.setRegistrationTime(new Date(System.currentTimeMillis()));
        newUser.setPhoneNumber(phoneNumber);
        newUser.setApplicationReason(applicationReason);
        newUser.setSecurityQuestion(securityQuestion);
        newUser.setSecurityAnswer(securityAnswer);


        //新建用户
        if (!userService.saveUser(newUser)) {
            model.addAttribute("error", "注册用户失败");
        }
        ;

        // 注册成功，跳转到登录页面
        model.addAttribute("message", "注册申请已提交，等待管理员审核");
        return "teammember-register";
    }
}
